// pages/ideas/ideas.js
import {handleSort} from "../utils/sortFunc";
import {currentTime} from "../utils/currentTimeFunc";
import Toast from '../../miniprogram_npm/vant-weapp/toast/toast';
const app = getApp();
const db = wx.cloud.database();

const opinions_col = db.collection('opinions');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        value: "",  // 手机号码和文本框输入框值
        textNum: "0",  //意见的字数初始化
        isLoading: false,
        wordColor: "black",
        showDialog: false,
        errorWord: "", //手机号码校验文字
        dataLength: "",  //数据长度
        opinionList: [],  //意见数据
        opinionListTwo: [],  //意见数据
        imgSrc: "../../images/delete.png",
        isshowLoading: false,
        isshowSwipe: true,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 状态栏样式
        wx.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#000000',
        });
        this.loadOpinions();
    },

    // 获取文本框中输入的字数
    getTexts: function(e) {
      var newNum = e.detail.value.length;
      this.setData({
        textNum: newNum
      })
    },

    // 请求意见的数据
    loadOpinions: function(){
      var self = this;
      opinions_col.get().then(
        res => {
          self.data.dataLength = res.data.length - 1;
          self.data.opinionList = res.data;
        }
      );
    },

    // 提交意见事件
    submit: function(e) {
      var self = this;
      var phoneReg = /^1[0-9]\d{9}$/;
      var newPhone = e.detail.value.telephone;
      var doTime = currentTime(new Date());
      var newLength = self.data.dataLength;
      var otherArr = self.data.opinionList;
      if(newPhone.length < 11 && newPhone > 0){
        this.setData({
          errorWord: "手机号码要有11位！",
        });
      }else if(newPhone.length == 0){
        this.setData({
          errorWord: "手机号码不能为空！",
        });
      }else if(!(phoneReg.test(newPhone))){
        this.setData({
          errorWord: "手机号码格式为数字！",
        });
        return false
      }else {
        self.setData({
          isLoading: true,
          errorWord: ""
        });
        var q = String(parseInt(otherArr[newLength]._id) + 1);
        var newuserId = app.globalData.userId;
        // 添加数据到数据库
        opinions_col.add({
          data: {
            _id: q,
            telephone: newPhone,
            text: e.detail.value.text,
            time: doTime,
            userId: newuserId,
          },
          success: () => {
            setTimeout( function(){
              self.setData({
                isLoading: false,
                value: "",
                textNum: "0",
              });
              wx.showToast({
                title: '提交意见成功',
                icon: 'success',
                duration: 2000
              })        
            },1000);
            self.onLoad();
          },
          fail: err => {
            self.setData({
              isLoading: false,
              value: "",
              textNum: "0",
            });
            wx.showToast({
              icon: 'none',
              title: '提交意见失败'
            });
            self.onLoad();
            console.error('失败：', err)
          }
        })
      }
    },

    // 查看已提交意见事件
    lookThing: function() {
      let newOpinion = this.data.opinionList;
      this.data.opinionListTwo = this.data.opinionList;
      newOpinion = handleSort(newOpinion);
      this.setData({
        wordColor: "red",
        showDialog: true,
        opinionList: newOpinion,
      })
    },
  
    // 模态框关闭
    onClose: function() {
      this.setData({ 
        showDialog: false,
        wordColor: "black",
        opinionList: this.data.opinionListTwo,
       });
    },

    // 删除意见
    deleteOne: function(work) {
      var self = this;
      var newId = work.currentTarget.dataset.opinionid;
      opinions_col.doc(newId).remove({
        success: function(){
          opinions_col.watch({
            onChange: function(snapshot) {
              let afterdatas = snapshot.docs;
              var n = handleSort(afterdatas);
              self.setData({
                isshowLoading: true,
                isshowSwipe: false,
              });
              setTimeout( function(){
                self.data.opinionListTwo = afterdatas;
                self.setData({
                  opinionList: n,
                  isshowLoading: false,
                  isshowSwipe: true,
                })
              },2000);
            },
            onError: function(err) {
              console.error('error', err)
            }
          });
          wx.showToast({
            title: '删除成功！',
            icon: 'success',
            duration: 800
          });      
        }
      })
    },

    // 滑块异步关闭
    onSwipeClose(event) {
      const { position, instance } = event.detail;
      switch (position) {
        case 'cell':
          instance.close();
          break;
        case 'right':
          instance.close();
          break;
      }
    },

    // 点击跳转到详情
    selectOne: function (event) {
      Toast.loading({
        duration: 1100,
        message: '加载中...',
        forbidClick: true,
        zIndex: 1000,
        onClose: () => {
          // 携带id跳转详情页面
          var id = event.currentTarget.dataset.opinionid;
          wx.navigateTo({
            url: '/pages/ideaDetails/ideaDetails?id='+id,
          })
        },
      });
    },

    // 打开本地图片上传
    openImg: function() {
        wx.chooseImage({
            count: 3, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
              // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
              var tempFilePaths = res.tempFilePaths
              console.log(tempFilePaths )
            },
            //回调函数
            complete:function(){
              console.log("--complete--")
            }
          })
    }
})